// pages/stats/stats.js
import * as echarts from "../../components/ec-canvas/echarts.min"
const db = wx.cloud.database()

function setoption(chart, countWeekDays) {
  const option = {
    tooltip: {
      trigger: 'axis',
      shadowBlur: 0, // 关闭阴影模糊度
      shadowColor: 'transparent', // 设置阴影颜色为透明
    },
    color: "#866FFD",
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"],
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {  // 增加此配置
          interval: 0,  // 强制显示所有标签      
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: 'Direct',
        type: 'bar',
        barWidth: '60%',
        data: countWeekDays
      }
    ]
  };
  chart.setOption(option)
}

function pieChart(chart, array) {
  const option = {
    tooltip: {
      trigger: 'item',
      shadowBlur: 0, // 关闭阴影模糊度
      shadowColor: 'transparent', // 设置阴影颜色为透明
      formatter: function (params) {
        return `${params.name}(${params.value}次)`
      }

    },
    color: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40', '#C9CBCF'],
    legend: {
      orient: 'horizontal',
      top: '0%',
      formatter: function (name) {
        const item = array.find(item => item.name === name);
        return `${item.name}(${item.value}次)`;
      }
    },
    series: [
      {
        type: 'pie',
        radius: '60%',
        center: ['50%', '60%'], // 设置饼图的中心位置
        data: array,
        labelLine: {
          show: true,
          length: 10,
          length2: 1
        },
        label: {
          formatter: function (params) {
            //console.log("params",params)
            return `${params.name}`
          }
        }
      }
    ]
  };
  chart.setOption(option)
}

function pieChartThree(chart, array) {
  const option = {
    tooltip: {
      trigger: 'item',
      shadowBlur: 0, // 关闭阴影模糊度
      shadowColor: 'transparent', // 设置阴影颜色为透明
      formatter: function (params) {
        return `${params.name}(${params.value}次)`
      }
    },
    color: ['#8B4513', '#5D4037', '#000000', '#808080', '#FFD700', '#008000'],
    legend: {
      orient: 'horizontal',
      top: '0%',
      formatter: function (name) {
        const item = array.find(item => item.name === name);
        return `${item.name}(${item.value}次)`;
      }
    },
    series: [
      {
        type: 'pie',
        radius: '60%',
        center: ['50%', '60%'], // 设置饼图的中心位置
        data: array,
        labelLine: {
          show: true,
          length: 10,
          length2: 1
        },
        label: {
          formatter: function (params) {
            //console.log("params",params)
            return `${params.name}`
          }
        }
      }
    ]
  };
  chart.setOption(option)
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    ec: {

    },
    ecPie: {},
    ecColorPie: {},
    babaTotalTime: 0,
    babaAverageTime: 0,
    babaTimes: 0,
    countWeekDays: []
  },

  async inquireDatabase() {
    const res = await wx.cloud.callFunction({
      name: 'inquireDatabase',
    })
    return res.result
  },

  async inquireUserInfo() {
    const res = await wx.cloud.callFunction({
      name: 'inquireUserInfo'
    })
    return res
  },

  async calculationBaba(result) {
    const user = await this.inquireUserInfo()
    console.log(user)
    let total = 0
    let avageTime = 0
    result.forEach(item => {
      total = total + Number(item.totalBaba)
    })
    avageTime = total / 60
    console.log(avageTime,total)
     db.collection('user').doc(user.result.data[0]._id).update({
      data: {
        babaMinutes: total,
        babaTimes:result.length
      },
      success: function(res) {
        console.log(res)
      }
    })

    this.setData({
      babaTotalTime: avageTime.toFixed(2),
      babaAverageTime: (avageTime/result.length).toFixed(2),
      babaTimes: result.length
    })
  },

  chartOneData(result) {
    console.log(result)
    const weekDays = result.map(item => item.weekDay);
    const weekDaysOrder = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
    const countweekDays = new Array(weekDaysOrder.length).fill(0);
    weekDays.forEach(day => {
      const index = weekDaysOrder.indexOf(day);
      if (index !== -1) { // 确保星期字符串有效
        countweekDays[index]++;
      } else {
        console.warn(`无效的星期值: ${day}`);
      }
    });
    this.setData({
      countWeekDays: countweekDays
    })
    console.log(this.data.countWeekDays)
    this.init_echart(this.data.countWeekDays)
  },

  chartTwoData(result) {
    const shape = result.map(item => item.babaShape)
    const shapeArray = ['坚果状', '干硬状', '有褶皱', '香蕉状', '软便', '略有形状', '水状']
    const timeArray = new Array(shapeArray.length).fill(0)
    shape.forEach(item => {
      const index = shapeArray.indexOf(item)
      if (index != -1) {
        timeArray[index]++
      } else {
        console.log("无效")
      }
    })
    const array = timeArray.map((value, index) => ({
      value: value,
      name: shapeArray[index]
    }))
    const filterArray = array.filter(item => item.value !== 0)
    this.init_echartTwo(filterArray)
  },

  chartThreeData(result) {
    const resultArray = result.map(item => item.babaColor)
    const colorArray = ['褐色', '深褐色', '黑色', '灰色', '黄色', '绿色']
    let array = new Array(colorArray.length).fill(0)
    resultArray.forEach(item => {
      const index = colorArray.indexOf(item)
      if (item) {
        array[index]++
      } else {
        console.log('错误')
      }
    })
    array = array.map((value, index) => ({
      value: value,
      name: colorArray[index]
    }))
    array = array.filter(item => item.value !== 0)
    this.init_echartThree(array)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    //const queryResult = await this.inquireDatabase()
    // const res = wx.getStorageSync('dataBaseResult')
    // const result = res.data
    // this.calculationBaba(result)
    // this.chartOneData(result)
    // this.chartTwoData(result)
    // this.chartThreeData(result)
  },

  // 初始化图表
  init_echart(countWeekDays) {
    this.Component = this.selectComponent('#mychart-one');
    this.Component.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      });
      setoption(chart, countWeekDays)
      this.chart = chart;
      return chart;
    });
  },

  init_echartTwo(array) {
    this.Component = this.selectComponent('#mychart-two');
    this.Component.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      });
      pieChart(chart, array)
      this.chart = chart;
      return chart;
    });
  },

  init_echartThree(array) {
    this.Component = this.selectComponent('#mychart-three');
    this.Component.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      });
      pieChartThree(chart, array)
      this.chart = chart;
      return chart;
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    const result = wx.getStorageSync('dataBaseResult')
    if (!result) {
      const res = await this.inquireDatabase()
      wx.setStorage({
        key: 'dataBaseResult',
        data: res
      })
    }
    this.calculationBaba(result.data)
    this.chartOneData(result.data)
    this.chartTwoData(result.data)
    this.chartThreeData(result.data)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})